package org.hengguan.api.contest.component;


import lombok.extern.slf4j.Slf4j;
import org.hengguan.api.contest.exception.OperationException;
import org.hengguan.api.contest.exception.SystemException;
import org.hengguan.api.contest.vo.ExceptionVo;
import org.hengguan.api.contest.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	@Value("${spring.servlet.multipart.max-file-size}")
	private String maxFileSize;
	@Value("${spring.servlet.multipart.max-request-size}")
	private String maxRequestSize;
//	MethodArgumentNotValidException
	@ExceptionHandler({BindException.class})
	public ResponseVo<ExceptionVo<Exception>> bindExceptionHandler(BindException ex) {
		ExceptionVo<Exception> exceptionVo = new ExceptionVo<>(ex);
		return ResponseVo.error(exceptionVo.getExMsg());
	}
	@ExceptionHandler({MaxUploadSizeExceededException.class})
    public ResponseVo<ExceptionVo<Exception>> maxUploadSizeExceptionHandler() {
        return ResponseVo.error("文件大小超出限制，单个文件大小不超过"+maxFileSize+"，总大小不超过"+maxRequestSize);
    }
	
	@ExceptionHandler({OperationException.class})
	public ResponseVo<ExceptionVo<Exception>> operationExceptionHandler(OperationException ex) {
		ExceptionVo<Exception> exceptionVo = new ExceptionVo<>(ex);
		return ResponseVo.error(exceptionVo.getExMsg());
	}
	@ExceptionHandler({HttpMediaTypeNotSupportedException.class})
	public ResponseVo<ExceptionVo<Exception>> notSupportedMethodExceptionHandler(HttpMediaTypeNotSupportedException ex) {
		ExceptionVo<Exception> exceptionVo = new ExceptionVo<>(ex);
		return ResponseVo.error(exceptionVo.getExMsg());
	}
	@ExceptionHandler({SystemException.class})
	public ResponseVo<ExceptionVo<Exception>> systemExceptionHandler(SystemException ex) {
		ExceptionVo<Exception> exceptionVo = new ExceptionVo<>(ex);
		log.error("故障名称=======================>>"+exceptionVo.getExName());
		String exMsg = exceptionVo.getExMsg();
		log.error(exMsg);
		/*
		 * 	补充错误日志
		 */
		return ResponseVo.error(exMsg==null?"系统运行故障，请联系维护人员":exMsg);
	}
	@ExceptionHandler({Exception.class})
	public ResponseVo<ExceptionVo<Exception>> unknownExceptionHandler(Exception ex) {
		ExceptionVo<Exception> exceptionVo = new ExceptionVo<>(ex);
		log.error("未知异常名称=======================>>"+exceptionVo.getExName());
		log.error(exceptionVo.getExMsg(),ex);
		/*
		 * 	补充错误日志
		 */
		return ResponseVo.error("系统出现未知错误");
	}
}
